package client.comm.commlib.dialog

import android.app.ProgressDialog
import android.content.Context
import androidx.lifecycle.viewModelScope
import client.comm.commlib.ContextProvider
import client.comm.commlib.base.BaseAppViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Call
import java.io.*

//下载更新包dialog

class UpdateVersionDialog(context: Context?, viewModel: BaseAppViewModel) :
    ProgressDialog(context) {
    companion object {
        val GET_UNKNOWN_APP_SOURCES = 0x999
    }

    val viewModel: BaseAppViewModel
    private lateinit var downUrl: String

    init {
        this.viewModel = viewModel
        setProgressStyle(STYLE_HORIZONTAL)
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setTitle("正在更新数据...")
        max = 100
    }

    fun startDown(url: String) {
        this.downUrl = url
        show()
        progress = 0
        viewModel.viewModelScope.launch {
            withContext(Dispatchers.IO) {

                var currentLength: Long = 0
                var os: OutputStream? = null
                var `is`: InputStream? = null //获取下载输入流
                var totalLength: Long = 0
                try {

                    val file = File(ContextProvider.get().apkPath)
                    //通过Url得到文件并创建本地文件
                    if (!file.parentFile.exists()) {
                        file.parentFile.mkdirs()
                    }
                    if (file.exists()) {
                        file.delete()
                    }
                    file.createNewFile()
                    val mCall: Call<ResponseBody> =
                        viewModel.iServer.downloadFile(url)
                    val response = mCall.execute()
                    `is` = response.body()!!.byteStream()
                    totalLength = response.body()!!.contentLength()
                    os = FileOutputStream(file) //输出流
                    var len: Int
                    val buff = ByteArray(1024)
                    while (`is`.read(buff).also { len = it } != -1) {
                        os.write(buff, 0, len)
                        currentLength += len.toLong()
                        //计算当前下载百分比，并经由回调传出
                        withContext(Dispatchers.Main) {
                            progress = ((100 * currentLength / totalLength).toInt())
                        }
                    }
                    //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径

                } catch (e: Exception) {
                    e.printStackTrace()


                } finally {
                    if (totalLength > 0 && (100 * currentLength / totalLength).toInt() == 100) { //下载完成
                        withContext(Dispatchers.Main) {
                            done?.run { this.invoke() }
                            cancel()
                        }
                    } else {
                        withContext(Dispatchers.Main) {
                            error?.run { this.invoke() }
                        }
                    }

                    if (os != null) {
                        try {
                            os.close() //关闭输出流
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                    if (`is` != null) {
                        try {
                            `is`.close() //关闭输入流
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }
            }
        }
    }

    open var done: (() -> Unit)? = null
    open var error: (() -> Unit)? = null
}